<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const arr = [
            { id: 1, pid: '', name: '财务部' },
            { id: 2, pid: 1, name: '财务核算部' },
            { id: 3, pid: 2, name: '财务核算分部' },
            { id: 4, pid: '', name: '人事部' },
            { id: 5, pid: 4, name: '杭州人事部' }
        ]
        
        function fn(arr,pid){
            const tempArr = []
            arr.forEach(item=>{
                if(item.pid === pid){
                    tempArr.push(item)
                    item.children = fn(arr,item.id)
                }
            })
            return tempArr 
        }


       console.log( fn(depts,''));

        // const newArr = []
        // arr.forEach(item => {
        //     if (item.pid === '') {
        //         const temArr = []
        //         arr.forEach(item1 => {
        //             if (item1.pid === item.pid) {
        //                 temArr.push(item1)
        //                 const temArr1 = []
        //             }
        //         })
        //         item.children = temArr
        //         newArr.push(item)
        //     }
        // })
        console.log(newArr)
    </script>
</body>

</html>